// 控制器，操作对象
const jwt = require('jsonwebtoken')
const userModel = require('../model/User')
const secret = 'lgx_jwt_secret' //秘钥

// 注册
exports.createUser = async ctx => {
    let { body } = ctx.request
    try {
        if (!body.username || !body.password) {
            ctx.sendErr(301, '用户输入信息不能为空')
            return
        }
        let list = await userModel.findAll({where: {name: body.username}})
        if (!list.length) {
           const user = await userModel.create({name: body.username , password: body.password})
            ctx.send({user}, '注册成功')
        } else {
            ctx.sendErr(301, '用户名已经存在')
        }

    } catch (e) {
        console.log(e)
        throw (e)
    }

}

// 登录
exports.login = async ctx => {
    let { body } = ctx.request
    console.log(body.username)
    console.log(body.password)
    try {
        if (!body.username || !body.password) {
            ctx.sendErr(301, '用户输入信息不能为空')
            return
        }
        let user = await userModel.findOne({where: {name: body.username}})
        if (!user) {
            ctx.sendErr(301, '用户不存在，请先注册账户！')
        } else {
            if (body.password.toString() === user.password) {
                let token = jwt.sign({data: user, exp: Math.floor(Date.now() / 1000) + (60 * 60)}, secret)
                let data = Object.assign({}, {user, token})
                ctx.send(data, '登录成功')
            } else {
                ctx.sendErr(301, '登录密码错误')
            }
        }

    } catch (e) {
        console.log(e)
        throw (e)
    }
}

exports.find = async ctx => {
    await userModel.findOne({ where: {name: 'tttt'} }).then(res => {
        ctx.response.body = res
    })
}

// 获取用户列表
exports.findAll = async ctx => {
    console.log('查询所有用户')
    ctx.set("Content-Type", "application/json;charset=utf-8");
    let userList = await userModel.findAll()
    ctx.body = {
        code: 200,
        data: {
            list: userList
        }
    }
}
exports.max = async ctx => {
    let phone = await userModel.max('phone')
    console.log(phone)
    await userModel.findOne({where: {phone: phone}}).then(res => {
        ctx.response.body = res
    })
}
